package com.du.ssm.controller;

import com.du.ssm.pojo.Employee;
import com.du.ssm.pojo.Message;
import com.du.ssm.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : DuJiabao
 * @Project : ssm
 * @Time : 2021/4/11 18:45
 * @Desc :
 */
@Controller
public class EmployeeController {
  EmployeeService employeeService;

  /**
   * 修改employee
   * @return
   */
  @ResponseBody
  @RequestMapping(value ="/emp", method = RequestMethod.PUT)
  public Message updateEmp(Employee employee) {
    System.out.println("     "+employee);
    employeeService.updateEmp(employee);
    return Message.getSuccessMessage();
  }

  /**
   * 检查用户名是否存在
   * @param empName
   * @return
   */
  @ResponseBody
  @RequestMapping("/checkEmpName")
  public Message checkEmpName(String empName) {
    boolean res = employeeService.checkEmpName(empName);
    if (res)
      return Message.getSuccessMessage();
    else
      return Message.getFailureMessage();
  }

  @ResponseBody
  @RequestMapping(value="/emp", method= RequestMethod.POST)
  public Message insertEmployee(Employee employee) {
    System.out.println(employee);
    int res = employeeService.insertEmployee(employee);
    System.out.println(res);
    return Message.getSuccessMessage();
  }

  @ResponseBody
  @RequestMapping("/empsWithJson")
  public Message getEmpsWithJson(@RequestParam(value="pn", defaultValue="1") Integer pn) {
    // 设置起始页码，页面数据数
    PageHelper.startPage(pn, 5);
    List<Employee> emps = employeeService.getAllEmployees();
    // 打包一个页面信息。navigatePage参数代表下标导航的那些页面有多少个
    PageInfo<Employee> pageInfo = PageInfo.of(emps, 5);
    return Message.getSuccessMessage().add("pageInfo", pageInfo);
  }


  @RequestMapping("/emps")
  public String getEmps(@RequestParam(value="pn", defaultValue="1") Integer pn, Model model) {
    // 设置起始页码，页面数据数
    PageHelper.startPage(pn, 5);
    List<Employee> emps = employeeService.getAllEmployees();
    // 打包一个页面信息。navigatePage参数代表下标导航的那些页面有多少个
    PageInfo<Employee> pageInfo = PageInfo.of(emps, 5);
    model.addAttribute("pageInfo", pageInfo);
    return "list";
  }

  @Autowired
  public void setEmployeeService(EmployeeService employeeService) {
    this.employeeService = employeeService;
  }
}
